import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/pick/ai/ai_model_logic.dart';
import 'package:ball_lion/entity/ai/ai_item_entity.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/card.dart';
import 'package:ball_lion/module/pick/ai/ai_type.dart';

class AiLmItem extends StatelessWidget {
  final CardStyle? cardStyle;
  final AiItemEntity item;
  final String? ticketName;
  final EdgeInsets? margin;
  final ValueChanged<bool>? onChange;
  final Function()? onTap;

  AiLmItem(
      {super.key,
      this.cardStyle,
      required this.item,
      this.onChange,
      this.margin,
      this.onTap,
      this.ticketName});

  late final AiModelLogic logic = Get.find<AiModelLogic>(tag: AiType.lm.tag);

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        if (item.isOpen != 1) ...[
          Block(
              cardStyle: cardStyle ??
                  CardStyle(
                    margin: margin ?? const EdgeInsets.only(bottom: 8),
                    padding: const EdgeInsets.only(top: 8, bottom: 12),
                  ),
              onTap: () => Get.toNamed(Routes.aiPay, arguments: AiType.lm),
              child: Column(children: [
                Stack(
                  alignment: AlignmentDirectional.topCenter,
                  children: [
                    Image.asset(Utils.getImgPath("ai_lock_back.png")),
                    Positioned(
                      bottom: 35,
                      child: Column(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            ShaderMask(
                              shaderCallback: (Rect bounds) =>
                                  const LinearGradient(
                                colors: [
                                  Colours.goldFFF3DC,
                                  Colours.goldFFD8C2
                                ],
                                begin: Alignment.topCenter,
                                end: Alignment.bottomCenter,
                              ).createShader(bounds),
                              child: QsText(item.aiIndex ?? "",
                                  fontSize: 24,
                                  color: Colours.white,
                                  fontFamily: "YouShe",
                                  height: 1),
                            ),
                            QsText(item.aiIndexName ?? "",
                                fontSize: 12, color: Colours.goldFFD8C2),
                            Container(height: 1)
                          ]),
                    )
                  ],
                ),
                Container(height: 8),
                const QsText("多项数据表明，本场比赛有可能爆冷")
              ]))
        ] else ...[
          Block(
              cardStyle: cardStyle ??
                  CardStyle(
                      margin: margin ?? const EdgeInsets.only(bottom: 8),
                      padding: const EdgeInsets.fromLTRB(8, 12, 8, 10)),
              onTap: () => Get.toNamed(Routes.aiDetail,
                  arguments: AiType.lm,
                  parameters: {"id": item.matchId.toString()}),
              child: Column(
                children: [
                  top(),
                  Container(height: 12),
                  middle(),
                  Container(height: 12),
                  bottom()
                ],
              ))
        ],
        if (item.aiResult != null && item.aiResult != "") ...[
          Positioned(
              top: 0,
              right: 0,
              child: Image.asset(height: 20, Utils.getImgPath("ai_tag.png"))),
          Positioned(
            top: 0,
            right: 0,
            child: Container(
              width: 73,
              height: 18,
              alignment: Alignment.center,
              child: QsText(item.aiResult ?? "",
                  fontSize: 12, color: Colours.white),
            ),
          )
        ]
      ],
    );
  }

  Widget top() {
    return DefaultTextStyle(
      style: const TextStyle(color: Colours.grey66, fontSize: 11),
      child: GestureDetector(
        onTap: () =>
            Get.toNamed(Routes.leagueDetail, arguments: "${item.leagueId}"),
        child: Row(
          children: [
            QsText(item.leagueName ?? "", needCenter: true),
            Container(width: 6),
            QsText(
              DateTime.tryParse(item.matchTime ?? "")
                  ?.formatedString("MM-dd HH:mm"),
              needCenter: true,
            ),
            Container(width: 6),
            QsText(ticketName ?? (item.matchNo ?? ""), needCenter: true)
          ],
        ),
      ),
    );
  }

  Widget middle() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () => Get.toNamed(Routes.zqMatchDetail, arguments: item.matchId),
      child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Expanded(child: team(item, true)),
        QsText(
          item.guestScore90 != null && item.homeScore90 != null
              ? "${item.homeScore90}-${item.guestScore90}"
              : "vs",
          fontSize: 18,
          color: const Color(0xFF4D3A47),
          fontWeight: FontWeight.w500,
          fontFamily: "Din",
        ).paddingSymmetric(horizontal: 2),
        Expanded(child: team(item, false))
      ]),
    );
  }

  Widget bottom() {
    List<String> option = [
      if (item.aiIndex.hasValue) "${item.aiIndex}",
      if (item.aiOption!.first.option.hasValue)
        item.aiOption!.first.option ?? ""
    ];
    List<String> optionName = [
      if (item.aiIndex.hasValue) "${item.aiIndexName}",
      if (item.aiOption!.first.option.hasValue) "建议"
    ];
    return GestureDetector(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: List<Widget>.generate(
            option.length,
            (index) => Expanded(
                  child: Container(
                    height: 83,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Colours.greyF7FAFF,
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(color: Colours.greyCC, width: 0.5)),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        QsText(optionName[index], color: Colours.grey66),
                        QsText(option[index],
                            fontSize: index == 0 ? 28 : 24,
                            color: Colours.main,
                            fontFamily: "YouShe",
                            height: index == 0 ? 1 : 1.17),
                        if (index == 0 && item.level.hasValue)
                          RatingBar(
                              initialRating: (item.level?.toDouble() ?? 0) / 2,
                              allowHalfRating: true,
                              itemCount: 5,
                              itemSize: 16,
                              ignoreGestures: true,
                              unratedColor: Colours.grey99,
                              ratingWidget: RatingWidget(
                                  full: Image.asset(
                                      width: 16,
                                      color: Colours.main,
                                      Utils.getImgPath(
                                          "match_info_star_on.png")),
                                  half: Image.asset(
                                      width: 16,
                                      Utils.getImgPath(
                                          "match_info_star_half.png")),
                                  empty: Image.asset(
                                      width: 16,
                                      Utils.getImgPath(
                                          "match_info_star_off.png"))),
                              onRatingUpdate: (rating) => 0)
                        else if (index == 1)
                          const QsText("仅供参考", color: Colours.grey66)
                      ],
                    ),
                  ),
                )).insertEvery(Container(width: 9)),
      ),
    );
  }

  Widget team(AiItemEntity item, bool isHome) {
    List<Widget> list = [
      CachedNetworkImage(
          width: 28,
          height: 28,
          placeholder: (context, url) => Styles.placeholderIcon(),
          errorWidget: (
            context,
            url,
            error,
          ) =>
              Image.asset(Utils.getImgPath("zq_placeholder.png")),
          imageUrl: (isHome ? item.homeLogo : item.guestLogo) ?? ""),
      Container(width: 4),
      Flexible(
        child: QsText(
          (isHome ? item.homeName : item.guestName) ?? "",
          textAlign: isHome ? TextAlign.left : TextAlign.right,
          fontSize: 15,
          fontWeight: FontWeight.w500,
        ),
      ),
      Container(width: 2),
      if ((isHome ? item.homeRanking : item.guestRanking).hasValue)
        QsText("[${isHome ? item.homeRanking : item.guestRanking}]",
            fontSize: 11, color: Colours.grey99)
    ];
    return Row(
        mainAxisAlignment:
            isHome ? MainAxisAlignment.start : MainAxisAlignment.end,
        children: isHome ? list : list.reversed.toList());
  }
}
